package com.xyqlx.paddydoctor.data;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xyqlx.paddydoctor.FlaskServerService;
import com.xyqlx.paddydoctor.data.model.LoggedInUser;
import com.xyqlx.paddydoctor.data.model.LoginUser;

import java.io.IOException;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Class that handles authentication w/ login credentials and retrieves user information.
 */
public class LoginDataSource {

    public Result<LoggedInUser> login(String username, String password) {

        try {
            LoginUser user=new LoginUser(username,password);
            Gson gson=new Gson();
            String obj=gson.toJson(user);
            Retrofit retrofit=new Retrofit.Builder().baseUrl(FlaskServerService.HttpConfig.BASE_URL).build();
            RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),obj);
            FlaskServerService serverService = retrofit.create(FlaskServerService.class);
            retrofit2.Call<ResponseBody> data = serverService.login(body);
            ResponseBody responseBody = data.execute().body();
            JsonObject document = JsonParser.parseString(responseBody.string()).getAsJsonObject();

            // TODO 异常处理
            if(document.has("user")){
                String id = document.get("user").getAsJsonObject().get("id").getAsString();
                String token = document.get("user").getAsJsonObject().get("token").getAsString();
                String location = document.get("user").getAsJsonObject().get("location").getAsString();
                LoggedInUser loggedInUser =
                        new LoggedInUser(id, username, token, location);
                return new Result.Success<>(loggedInUser);
            }
            if(document.has("message")){
                return new Result.Error(new Exception(document.get("message").getAsString()));
            }
            return new Result.Error(new Exception("登录失败，可能是服务器错误"));
//            data.enqueue(new Callback<ResponseBody>() {
//                @Override
//                public void onResponse(retrofit2.Call<ResponseBody> call, Response<ResponseBody> response) {
//                    Log.d("", "onResponse: --ok--"+response.body());
//                    try {
//                        Log.d("", "onResponse: --ok--"+response.body().string());
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//                @Override
//                public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
//                    Log.d("", "onResponse: --err--"+t.toString());
//                } });
        } catch (Exception e) {
            return new Result.Error(new IOException("登录失败", e));
        }
    }

    public void logout() {
        // TODO: revoke authentication
    }


}